import 'package:flutter/material.dart';
import '../../config/theme/theme_manager.dart';
import 'common_button.dart';

/// 通用对话框组件
/// 提供统一的对话框样式和功能
class CommonDialog {
  /// 显示确认对话框
  static Future<bool?> showConfirm(
    BuildContext context, {
    String? title,
    String? content,
    String? confirmText,
    String? cancelText,
    VoidCallback? onConfirm,
    VoidCallback? onCancel,
    bool barrierDismissible = true,
    Color? confirmColor,
    Color? cancelColor,
    IconData? icon,
    Color? iconColor,
  }) {
    return showDialog<bool>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (context) => _ConfirmDialog(
        title: title,
        content: content,
        confirmText: confirmText,
        cancelText: cancelText,
        onConfirm: onConfirm,
        onCancel: onCancel,
        confirmColor: confirmColor,
        cancelColor: cancelColor,
        icon: icon,
        iconColor: iconColor,
      ),
    );
  }

  /// 显示信息对话框
  static Future<void> showInfo(
    BuildContext context, {
    String? title,
    String? content,
    String? buttonText,
    VoidCallback? onPressed,
    bool barrierDismissible = true,
    IconData? icon,
    Color? iconColor,
  }) {
    return showDialog<void>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (context) => _InfoDialog(
        title: title,
        content: content,
        buttonText: buttonText,
        onPressed: onPressed,
        icon: icon,
        iconColor: iconColor,
      ),
    );
  }

  /// 显示成功对话框
  static Future<void> showSuccess(
    BuildContext context, {
    String? title,
    String? content,
    String? buttonText,
    VoidCallback? onPressed,
    bool barrierDismissible = true,
  }) {
    return showInfo(
      context,
      title: title ?? '成功',
      content: content,
      buttonText: buttonText,
      onPressed: onPressed,
      barrierDismissible: barrierDismissible,
      icon: Icons.check_circle,
      iconColor: Colors.green,
    );
  }

  /// 显示错误对话框
  static Future<void> showError(
    BuildContext context, {
    String? title,
    String? content,
    String? buttonText,
    VoidCallback? onPressed,
    bool barrierDismissible = true,
  }) {
    return showInfo(
      context,
      title: title ?? '错误',
      content: content,
      buttonText: buttonText,
      onPressed: onPressed,
      barrierDismissible: barrierDismissible,
      icon: Icons.error,
      iconColor: Colors.red,
    );
  }

  /// 显示警告对话框
  static Future<void> showWarning(
    BuildContext context, {
    String? title,
    String? content,
    String? buttonText,
    VoidCallback? onPressed,
    bool barrierDismissible = true,
  }) {
    return showInfo(
      context,
      title: title ?? '警告',
      content: content,
      buttonText: buttonText,
      onPressed: onPressed,
      barrierDismissible: barrierDismissible,
      icon: Icons.warning,
      iconColor: Colors.orange,
    );
  }

  /// 显示加载对话框
  static Future<void> showLoading(
    BuildContext context, {
    String? message,
    bool barrierDismissible = false,
  }) {
    return showDialog<void>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (context) => _LoadingDialog(
        message: message,
      ),
    );
  }

  /// 显示自定义对话框
  static Future<T?> showCustom<T>(
    BuildContext context, {
    required Widget child,
    bool barrierDismissible = true,
    Color? backgroundColor,
    double? borderRadius,
    EdgeInsetsGeometry? padding,
    EdgeInsetsGeometry? margin,
  }) {
    return showDialog<T>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (context) => _CustomDialog(
        backgroundColor: backgroundColor,
        borderRadius: borderRadius,
        padding: padding,
        margin: margin,
        child: child,
      ),
    );
  }

  /// 显示底部弹窗
  static Future<T?> showBottomSheet<T>(
    BuildContext context, {
    required Widget child,
    bool isScrollControlled = false,
    bool isDismissible = true,
    bool enableDrag = true,
    Color? backgroundColor,
    double? borderRadius,
    EdgeInsetsGeometry? padding,
  }) {
    return showModalBottomSheet<T>(
      context: context,
      isScrollControlled: isScrollControlled,
      isDismissible: isDismissible,
      enableDrag: enableDrag,
      backgroundColor: Colors.transparent,
      builder: (context) => _BottomSheetDialog(
        backgroundColor: backgroundColor,
        borderRadius: borderRadius,
        padding: padding,
        child: child,
      ),
    );
  }
}

/// 确认对话框
class _ConfirmDialog extends StatelessWidget {
  final String? title;
  final String? content;
  final String? confirmText;
  final String? cancelText;
  final VoidCallback? onConfirm;
  final VoidCallback? onCancel;
  final Color? confirmColor;
  final Color? cancelColor;
  final IconData? icon;
  final Color? iconColor;

  const _ConfirmDialog({
    this.title,
    this.content,
    this.confirmText,
    this.cancelText,
    this.onConfirm,
    this.onCancel,
    this.confirmColor,
    this.cancelColor,
    this.icon,
    this.iconColor,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    return Dialog(
      backgroundColor: themeManager.cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (icon != null) ...[
              Icon(
                icon,
                size: 48,
                color: iconColor ?? themeManager.primaryColor,
              ),
              const SizedBox(height: 16),
            ],
            if (title != null) ...[
              Text(
                title!,
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: themeManager.contrastColor,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 12),
            ],
            if (content != null) ...[
              Text(
                content!,
                style: TextStyle(
                  fontSize: 14,
                  color: themeManager.contrastColor.withOpacity(0.8),
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
            ],
            Row(
              children: [
                Expanded(
                  child: CommonButton(
                    text: cancelText ?? '取消',
                    type: ButtonType.outline,
                    color: cancelColor ??
                        themeManager.contrastColor.withOpacity(0.6),
                    onPressed: () {
                      Navigator.of(context).pop(false);
                      onCancel?.call();
                    },
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: CommonButton(
                    text: confirmText ?? '确认',
                    type: ButtonType.primary,
                    onPressed: () {
                      Navigator.of(context).pop(true);
                      onConfirm?.call();
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

/// 信息对话框
class _InfoDialog extends StatelessWidget {
  final String? title;
  final String? content;
  final String? buttonText;
  final VoidCallback? onPressed;
  final IconData? icon;
  final Color? iconColor;

  const _InfoDialog({
    this.title,
    this.content,
    this.buttonText,
    this.onPressed,
    this.icon,
    this.iconColor,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    return Dialog(
      backgroundColor: themeManager.cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (icon != null) ...[
              Icon(
                icon,
                size: 48,
                color: iconColor ?? themeManager.primaryColor,
              ),
              const SizedBox(height: 16),
            ],
            if (title != null) ...[
              Text(
                title!,
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: themeManager.contrastColor,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 12),
            ],
            if (content != null) ...[
              Text(
                content!,
                style: TextStyle(
                  fontSize: 14,
                  color: themeManager.contrastColor.withOpacity(0.8),
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
            ],
            SizedBox(
              width: double.infinity,
              child: CommonButton(
                text: buttonText ?? '确定',
                onPressed: () {
                  Navigator.of(context).pop();
                  onPressed?.call();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 加载对话框
class _LoadingDialog extends StatelessWidget {
  final String? message;

  const _LoadingDialog({
    this.message,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    return Dialog(
      backgroundColor: themeManager.cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(
              valueColor:
                  AlwaysStoppedAnimation<Color>(themeManager.primaryColor),
            ),
            if (message != null) ...[
              const SizedBox(height: 16),
              Text(
                message!,
                style: TextStyle(
                  fontSize: 14,
                  color: themeManager.contrastColor,
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ],
        ),
      ),
    );
  }
}

/// 自定义对话框
class _CustomDialog extends StatelessWidget {
  final Widget child;
  final Color? backgroundColor;
  final double? borderRadius;
  final EdgeInsetsGeometry? padding;
  final EdgeInsetsGeometry? margin;

  const _CustomDialog({
    required this.child,
    this.backgroundColor,
    this.borderRadius,
    this.padding,
    this.margin,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    return Dialog(
      backgroundColor: backgroundColor ?? themeManager.cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(borderRadius ?? 16),
      ),
      child: Container(
        margin: margin,
        padding: padding ?? const EdgeInsets.all(24),
        child: child,
      ),
    );
  }
}

/// 底部弹窗对话框
class _BottomSheetDialog extends StatelessWidget {
  final Widget child;
  final Color? backgroundColor;
  final double? borderRadius;
  final EdgeInsetsGeometry? padding;

  const _BottomSheetDialog({
    required this.child,
    this.backgroundColor,
    this.borderRadius,
    this.padding,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    return Container(
      decoration: BoxDecoration(
        color: backgroundColor ?? themeManager.cardColor,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(borderRadius ?? 20),
          topRight: Radius.circular(borderRadius ?? 20),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 拖拽指示器
          Container(
            margin: const EdgeInsets.only(top: 12, bottom: 8),
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: themeManager.contrastColor.withOpacity(0.3),
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          Flexible(
            child: Container(
              padding: padding ?? const EdgeInsets.all(20),
              child: child,
            ),
          ),
        ],
      ),
    );
  }
}

/// 选择对话框
class SelectDialog<T> extends StatelessWidget {
  final String? title;
  final List<SelectOption<T>> options;
  final T? selectedValue;
  final ValueChanged<T>? onSelected;
  final bool allowMultiple;
  final List<T>? selectedValues;
  final ValueChanged<List<T>>? onMultipleSelected;

  const SelectDialog({
    super.key,
    this.title,
    required this.options,
    this.selectedValue,
    this.onSelected,
    this.allowMultiple = false,
    this.selectedValues,
    this.onMultipleSelected,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    return Dialog(
      backgroundColor: themeManager.cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        constraints: const BoxConstraints(maxHeight: 400),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (title != null) ...[
              Padding(
                padding: const EdgeInsets.all(20),
                child: Text(
                  title!,
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: themeManager.contrastColor,
                  ),
                ),
              ),
              Divider(color: themeManager.dividerColor),
            ],
            Flexible(
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: options.length,
                itemBuilder: (context, index) {
                  final option = options[index];
                  final isSelected = allowMultiple
                      ? selectedValues?.contains(option.value) ?? false
                      : selectedValue == option.value;

                  return ListTile(
                    leading: option.icon != null
                        ? Icon(
                            option.icon,
                            color: isSelected
                                ? themeManager.primaryColor
                                : themeManager.contrastColor.withOpacity(0.6),
                          )
                        : null,
                    title: Text(
                      option.label,
                      style: TextStyle(
                        color: isSelected
                            ? themeManager.primaryColor
                            : themeManager.contrastColor,
                        fontWeight:
                            isSelected ? FontWeight.w600 : FontWeight.normal,
                      ),
                    ),
                    subtitle: option.subtitle != null
                        ? Text(
                            option.subtitle!,
                            style: TextStyle(
                              color:
                                  themeManager.contrastColor.withOpacity(0.6),
                              fontSize: 12,
                            ),
                          )
                        : null,
                    trailing: isSelected
                        ? Icon(
                            allowMultiple ? Icons.check_box : Icons.check,
                            color: themeManager.primaryColor,
                          )
                        : (allowMultiple
                            ? Icon(
                                Icons.check_box_outline_blank,
                                color:
                                    themeManager.contrastColor.withOpacity(0.3),
                              )
                            : null),
                    onTap: () {
                      if (allowMultiple) {
                        final currentValues =
                            List<T>.from(selectedValues ?? []);
                        if (currentValues.contains(option.value)) {
                          currentValues.remove(option.value);
                        } else {
                          currentValues.add(option.value);
                        }
                        onMultipleSelected?.call(currentValues);
                      } else {
                        Navigator.of(context).pop(option.value);
                        onSelected?.call(option.value);
                      }
                    },
                  );
                },
              ),
            ),
            if (allowMultiple) ...[
              Divider(color: themeManager.dividerColor),
              Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: [
                    Expanded(
                      child: CommonButton(
                        text: '取消',
                        type: ButtonType.outline,
                        onPressed: () => Navigator.of(context).pop(),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: CommonButton(
                        text: '确定',
                        onPressed: () {
                          Navigator.of(context).pop(selectedValues);
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

/// 选择选项
class SelectOption<T> {
  final T value;
  final String label;
  final String? subtitle;
  final IconData? icon;

  const SelectOption({
    required this.value,
    required this.label,
    this.subtitle,
    this.icon,
  });
}
